package com.sc.es.controller.backend;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.sc.es.common.ApiResponse;
import com.sc.es.common.DataTableResponse;
import com.sc.es.common.HouseResult;
import com.sc.es.common.ServiceResult;
import com.sc.es.dto.QiNiuPutRet;
import com.sc.es.entity.House;
import com.sc.es.form.DatatableSearch;
import com.sc.es.form.HouseForm;
import com.sc.es.service.IAddressService;
import com.sc.es.service.IHouseService;
import com.sc.es.service.IQiNiuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author sc
 * Created on  2018/2/7
 */
@Controller
@RequestMapping("/admin")
public class HouseController {

    @Autowired
    private IHouseService houseService;
    @Autowired
    private Gson gson;
    @Autowired
    private IQiNiuService qiNiuService;

    /***
     * 上传图片
     * @param file
     * @return
     */
    @PostMapping(value = "/upload/photo",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    public ApiResponse uploadPhoto(@RequestParam("file")MultipartFile file){
        if(file.isEmpty()){
            return ApiResponse.ofStatus(ApiResponse.Status.NOT_VALID_PARAM);
        }

        try {
            InputStream stream = file.getInputStream();
            Response response = qiNiuService.uploadFile(stream);
            if(response.isOK()){
                QiNiuPutRet qiNiuPutRet = gson.fromJson(response.bodyString(), QiNiuPutRet.class);
                return ApiResponse.ofSuccess(qiNiuPutRet);
            }else {
                return ApiResponse.ofMessage(response.statusCode,response.getInfo());
            }
        }catch (QiniuException e){
            Response response = e.response;
            return ApiResponse.ofMessage(response.statusCode,response.getInfo());
        }
        catch (IOException e) {
            return ApiResponse.ofSuccess(ApiResponse.Status.INTERNAL_SERVER_ERROR);
        }
    }

    /***
     * 添加房源
     * @param houseForm
     * @param bindingResult
     * @return
     */
    @PostMapping("/add/house")
    @ResponseBody
    public ApiResponse addHouse(@Valid @ModelAttribute("form-house-add") HouseForm houseForm,
                                BindingResult bindingResult){
        if(bindingResult.hasErrors()){
             return new ApiResponse(HttpStatus.BAD_REQUEST.value(),
                     bindingResult.getAllErrors().get(0).getDefaultMessage(),
                     null);
        }
        if(houseForm.getPhotos().isEmpty()||houseForm.getCover()==null){
            return ApiResponse.ofMessage(HttpStatus.BAD_REQUEST.value(),
                    "必须上传图片并选择封面");
        }
        HouseResult result = houseService.save(houseForm);
        if(result.isSuccess()){
            return ApiResponse.ofSuccess(result);
        }
        return ApiResponse.ofStatus(ApiResponse.Status.INTERNAL_SERVER_ERROR);
    }

    /***
     * 房源列表
     * @param datatableSearch
     * @return
     */
    @PostMapping("/houses")
    @ResponseBody
    public DataTableResponse houses(@ModelAttribute DatatableSearch datatableSearch){
        ServiceResult result = houseService.findAllHouse(datatableSearch);
        DataTableResponse response = new DataTableResponse(ApiResponse.Status.SUCCESS);
        response.setDraw(datatableSearch.getDraw());
        response.setRecordsTotal(result.getTotal());
        response.setData(result.getResult());
        response.setRecordsFiltered(result.getTotal());
        return response;
    }

    /**
     * 编辑
     * @param houseForm
     * @param bindingResult
     * @return
     */
    @PostMapping("/house/edit")
    @ResponseBody
    public ApiResponse houseEdit(@Valid @ModelAttribute("form-house-edit")HouseForm houseForm,
                                 BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return ApiResponse.ofStatus(ApiResponse.Status.NOT_VALID_PARAM);
        }
        HouseResult houseResult = houseService.update(houseForm);
        if(houseResult.isSuccess()){
            return ApiResponse.ofStatus(ApiResponse.Status.SUCCESS);
        }
        return ApiResponse.ofStatus(ApiResponse.Status.INTERNAL_SERVER_ERROR);
    }

    /**
     * 设置封面
     * @param targetId
     * @param coverId
     * @return
     */
    @PostMapping("/house/cover")
    @ResponseBody
    public ApiResponse houseSetCover(@RequestParam("target_id")Integer targetId,
                                     @RequestParam("cover_id")Integer coverId){
        HouseResult result = houseService.setCover(targetId,coverId);
        if(result.isSuccess()){
            return ApiResponse.ofStatus(ApiResponse.Status.SUCCESS);
        }
        return ApiResponse.ofStatus(ApiResponse.Status.INTERNAL_SERVER_ERROR);
    }

    /***
     * 删除图片
     * @param id
     * @return
     */
    @DeleteMapping("/house/photo")
    @ResponseBody
    public ApiResponse deletePhoto(@RequestParam("id")Integer id){
        HouseResult houseResult = houseService.deletePhoto(id);
        if(houseResult.isSuccess()){
            return ApiResponse.ofStatus(ApiResponse.Status.SUCCESS);
        }
        return ApiResponse.ofStatus(ApiResponse.Status.INTERNAL_SERVER_ERROR);
    }

    /**
     * 发布房源
     * @param id
     * @return
     */
    @PutMapping("/house/operate/{id}/1")
    @ResponseBody
    public ApiResponse publishOne(@PathVariable("id")Integer id){
        HouseResult houseResult = houseService.changeStatusToPublish(id,true);
        if(houseResult.isSuccess()){
            return ApiResponse.ofStatus(ApiResponse.Status.SUCCESS);
        }
        return ApiResponse.ofStatus(ApiResponse.Status.INTERNAL_SERVER_ERROR);
    }

    /**
     * 下架房源
     * @param id
     * @return
     */
    @PutMapping("/house/operate/{id}/2")
    @ResponseBody
    public ApiResponse unpublishOne(@PathVariable("id")Integer id){
        HouseResult houseResult = houseService.changeStatusToPublish(id,false);
        if(houseResult.isSuccess()){
            return ApiResponse.ofStatus(ApiResponse.Status.SUCCESS);
        }
        return ApiResponse.ofStatus(ApiResponse.Status.INTERNAL_SERVER_ERROR);
    }

    /**
     * 删除房源
     * @param id
     * @return
     */
    @PutMapping("/house/operate/{id}/3")
    @ResponseBody
    public ApiResponse deleteOne(@PathVariable("id")Integer id){
        HouseResult houseResult = houseService.deleteHouse(id);
        if(houseResult.isSuccess()){
            return ApiResponse.ofStatus(ApiResponse.Status.SUCCESS);
        }
        return ApiResponse.ofStatus(ApiResponse.Status.INTERNAL_SERVER_ERROR);
    }
}
